﻿using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ZilLion.Service.Core.Infrastructure.Base;
using ZilLion.Service.TaskPlatform.Domain.Respository.Interface;

namespace ZilLion.Service.TaskPlatform.Controllers
{
    /// <summary>
    ///     任务包下载
    /// </summary>
    [Route("Api/TaskPlatform/DownloadTaskPackage")]
    [AllowAnonymous]
    public class TaskPackageDownloadController : ZilLionControllerBase
    {
        //响应的MimeType类型
        private const string MimeType = "application/octet-stream";

        private readonly ITaskModuleConfigRespository _taskModuleConfigRespository;
        private readonly ITaskPackageRespository _taskPackageRespository;

        public TaskPackageDownloadController(ITaskPackageRespository taskPackageRespository,
            ITaskModuleConfigRespository taskModuleConfigRespository)
        {
            _taskPackageRespository = taskPackageRespository;
            _taskModuleConfigRespository = taskModuleConfigRespository;
        }

        [HttpGet("{moduleid}")]
        public FileContentResult GetModulePackage(string moduleid)
        {
            var entity = _taskModuleConfigRespository.GetModuleConfigById(moduleid);
            if (entity != null)
                return DownloadOneTime(entity.Taskmodulepackagekey);

            throw new Exception("下载的模块包不存在");
        }


        /// <summary>
        ///     下载实现（不支持断点续传）
        /// </summary>
     
        /// <param name="packageKey"></param>
        /// <returns></returns>
        private FileContentResult DownloadOneTime(string packageKey)
        {
            //从图片中读取byte
            var fileStream = _taskPackageRespository.GetPackageBytes(packageKey);
            var mimeType = "application/octet-stream";
            return new FileContentResult(fileStream, mimeType);
        }
    }
}